package com.sansan.qiangji.controller.base;

import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import com.sansan.qiangji.form.base.DeviceAddForm;
import com.sansan.qiangji.form.base.DeviceEditForm;
import com.sansan.qiangji.form.base.DeviceListForm;
import com.sansan.qiangji.realize.base.DeviceReal;
import com.sansan.qiangji.resultVO.ResultVO;
import com.sansan.qiangji.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

@RestController
@RequestMapping("/device")
@CrossOrigin()
@Slf4j
public class DeviceController {

    @Autowired
    private DeviceReal deviceReal;


    @PostMapping("/addDevice")
    public ResultVO<Object> addDevice(@Valid @RequestBody DeviceAddForm deviceAddForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【设备新增】参数不正确，deviceAddForm={}",deviceAddForm);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        deviceReal.addDevice(deviceAddForm);
        return ResultVOUtil.success(null);
    }


    @PostMapping("/getDeviceList")
    public ResultVO<Object> getDeviceList(@Valid @RequestBody DeviceListForm form, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【设备查询】参数不正确，deviceAddForm={}",form);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        return ResultVOUtil.success(deviceReal.deviceList(form));
    }


    @PostMapping("/editDevice")
    public ResultVO<Object> editDevice(@Valid @RequestBody DeviceEditForm deviceEditForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【设备修改】参数不正确，deviceAddForm={}",deviceEditForm);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        deviceReal.editDevice(deviceEditForm);
        return ResultVOUtil.success(null);
    }


    @PostMapping("/deleteDevice")
    public ResultVO<Object> deleteDevice(@RequestParam(value = "deviceId") Integer deviceId){
        deviceReal.deleteDevice(deviceId);
        return ResultVOUtil.success(null);
    }
}
